package com.edu.dgut.controller;

import com.edu.dgut.dao.monthlysalesRepository;
import com.edu.dgut.entity.monthlysalesEntity;
import com.edu.dgut.service.mapObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/")
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
public class monthlysalesController {

    @Autowired
    private monthlysalesRepository montylysales;

    private mapObjectService mapObject = new mapObjectService();

    //查询所有月销售额
    @RequestMapping("getAllmonthlysales")
    @ResponseBody
    public Map<String, Object> findAll(){
        List<monthlysalesEntity> list = new ArrayList<>();
        list = montylysales.findAll();
        return mapObject.put(list);
    }

    //通过年月查找月销售额
    @RequestMapping("getByMonthlyDate")
    @ResponseBody
    public Map<String, Object> getByMonthlyDate(String year_month) {
        List<monthlysalesEntity> result = montylysales.findByDate(year_month);
        return mapObject.put(result);
    }

    //添加或修改月销售额信息
    @RequestMapping("modifyMonthlysales")
    @ResponseBody
    public Map<String, Object> saveOrModifyMonthlysales(@RequestBody monthlysalesEntity new_monthlysales) {
        String year_month = new_monthlysales.getDate();
        List<monthlysalesEntity> old_monthlysales = montylysales.findByDate(year_month);
        //如果输入的年月对应信息不存在，则插入新信息，否则修改对应信息
        if(old_monthlysales.size() != 0) {
            new_monthlysales.setMonthlysales_id(old_monthlysales.get(0).getMonthlysales_id());
        }
        new_monthlysales = montylysales.save(new_monthlysales);
        Map<String,Object> map = new HashMap<String,Object>();
        if(new_monthlysales != null) {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }

    //删除月销售额
    @RequestMapping("deleteByMonthlyDate")
    @ResponseBody
    public Map<String, Object> deleteByDailyDate(String year_month) {
        int i = montylysales.deleteByDate(year_month);
        Map<String,Object> map = new HashMap<String,Object>();
        if(i >= 1) {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }
}
